package org.testframe;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;

/**
 * js 执行器
 * @author 丁常磊
 * @date 2023/11/17 11:23
 */

public class JsExecutor {

    private static final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    private final String script;

    public JsExecutor(String script) {
        this.script = script;
    }

    public Object execute(FlowContext flowContext) {

        Bindings bindings = new SimpleBindings();
        JsContextVisitor jsContextVisitor = new JsContextVisitor(flowContext);
        bindings.put("ctx", jsContextVisitor);
        bindings.put("context", jsContextVisitor);


        try {
            return engine.eval(script, bindings);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
